package org.example.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.example.annotation.MessageController;
import org.example.pojo.*;
import org.example.service.BaselineService;
import org.example.service.LogService;
import org.example.service.NetInfoService;
import org.example.service.impl.*;
import org.springframework.web.bind.annotation.*;
import sun.nio.ch.Net;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.awt.peer.SystemTrayPeer;
import java.sql.Array;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.*;

/**
 * 包括硬件信息、mac信息在内的通用信息(BasicInfos)表控制层
 *
 * @author JSY2019
 * @since 2022-06-20 08:00:07
 * @version 1.0
 */
@MessageController
@RequestMapping("/basicInfo")
@Api(value = "包括硬件信息、mac信息在内的通用信息(BasicInfos)管理",tags = "包括硬件信息、mac信息在内的通用信息(BasicInfos)管理接口API")
@ApiResponses({
        @ApiResponse(code=400,message="请求参数不完整或者错误"),
        @ApiResponse(code=404,message="找不到页面"),
        @ApiResponse(code=405,message="请求方式不正确，比如后台接收是post，但前端请求的是get"),
        @ApiResponse(code=406,message="页面地址和接口名冲突"),
        @ApiResponse(code=415,message="请求格式不正确，前端可能没有把请求头修改为json，也可能前端请求的json对象没有转换为字符串"),
        @ApiResponse(code=500,message="后台服务逻辑错误")
})
public class premiereController {
    @Resource
    private BasicsServiceImpl basicsService;
    @Resource
    private HardwareServiceImpl hardwareService;
    @Resource
    private BaselineServiceImpl baselineService;
    @Resource
    private SystemServiceServiceImpl systemServiceService;
    @Resource
    private NetInfoServiceImpl netInfoService;
    @Resource
    private LogService logService;


    @RequestMapping(value = "/insertBasicHardware",method = RequestMethod.POST)
    @ApiOperation(value = "基础+硬件加入内容",notes = "基础+硬件加入内容",httpMethod = "POST")
    public String insertBasicHardware(@RequestBody BasicAndHardware bah){
        ObjectMapper mapper = new ObjectMapper();
        Logs log = mapper.convertValue(bah.getLog(), Logs.class);


        Basics basics = mapper.convertValue(bah.getBasic(), Basics.class);
        basics.setUname(log.getUname());
        basics.setTimestamp(Timestamp.valueOf(log.getTimestamp()));

        Hardware hardware = mapper.convertValue(bah.getHardware(),Hardware.class);
        hardware.setMac(log.getUname());
        hardware.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));
        hardware.setInfoPhysicalMemory(hardware.getInfoPhysicalMemory().toString());

        //添加到basic表中
        this.basicsService.insert(basics);
        //添加到hardware表中
        this.hardwareService.insert(hardware);
        //发送日志消息
        this.logService.saveLog(new Log(log));

        return "添加成功";
    }

    @RequestMapping(value = "/insertBaseCheck",method = RequestMethod.POST)
    @ApiOperation(value = "基础+基线检查加入内容",notes = "基础+基线检查加入内容",httpMethod = "POST")
    public String insertBaseCheck(@RequestBody BasicAndChecks bac){
        ObjectMapper mapper = new ObjectMapper();
        Logs log = mapper.convertValue(bac.getLog(),Logs.class);

        Basics basics = mapper.convertValue(bac.getBasic(), Basics.class);
        basics.setUname(log.getUname());
        basics.setTimestamp(Timestamp.valueOf(log.getTimestamp()));

        List<Checks> licheck = bac.getChecks();

        List<Baseline> libaseline = new LinkedList<>();
        for(Checks ch : licheck){
            Baseline bs = new Baseline();
            bs.setMac(log.getUname());
            bs.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));
            bs.setKey(ch.getKey());
            bs.setEvalued(ch.getEvalued());
            bs.setRelVal(ch.getRel_val());
            bs.setResult(ch.getResult());
            libaseline.add(bs);
        }
        //添加到basic表中
        this.basicsService.insert(basics);
        //添加到baseline表中
        this.baselineService.multiinsert(libaseline);
        //发送日志消息
        this.logService.saveLog(new Log(log));

        return "添加成功";
    }

    @RequestMapping(value = "/insertSysService",method = RequestMethod.POST)
    @ApiOperation(value = "系统服务检查加入内容",notes = "系统服务检查加入内容",httpMethod = "POST")
    public String insertSysService(@RequestBody SystemServiceReceive ss){
        ObjectMapper mapper = new ObjectMapper();
        Logs log = mapper.convertValue(ss.getLog(),Logs.class);
        List<ServiceReceive> liservice = ss.getService();

//        System.out.println(log);

        List<SystemService> lisystemserv= new LinkedList<>();
        for(ServiceReceive cr : liservice){
            SystemService bs = new SystemService();
            bs.setMac(log.getUname());
            bs.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));
            bs.setCaption(cr.getCaption());
            bs.setDescriptions(cr.getDescriptions());
            bs.setStartmode(cr.getStartmode());
            bs.setState(cr.getState());

            lisystemserv.add(bs);
        }

        //添加到syetemservice表中
        this.systemServiceService.multiinsert(lisystemserv);
        //发送日志消息
        this.logService.saveLog(new Log(log));

        return "添加成功";
    }

    @RequestMapping(value = "/insertNetInfo",method = RequestMethod.POST)
    @ApiOperation(value = "网络情况加入内容",notes = "网络情况加入内容",httpMethod = "POST")
    public String insertSysService(@RequestBody NetInfoReceive nir){
        ObjectMapper mapper = new ObjectMapper();
        Logs log = mapper.convertValue(nir.getLog(),Logs.class);

        NetInfo ni = new NetInfo();

        ni.setMac(log.getUname());
        ni.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));

        List<String> lis = nir.getPort();
        StringBuilder stb = new StringBuilder();
        for (String li : lis) {
            stb.append(li).append(",");
        }
        ni.setOpenport(stb.toString().substring(0,stb.toString().length()-1));

        //添加到net_info表中
        this.netInfoService.insert(ni);
        //发送日志消息
        this.logService.saveLog(new Log(log));

        return "添加成功";
    }

    @RequestMapping(value = "/insertLinuxProperties",method = RequestMethod.POST)
    @ApiOperation(value = "加入Linux内容",notes = "加入Linux内容",httpMethod = "POST")
    public String insertLinuxProperties(@RequestBody LinuxReceive lr){
        ObjectMapper mapper = new ObjectMapper();
        Logs log = mapper.convertValue(lr.getLog(),Logs.class);

        Basics basics = mapper.convertValue(lr.getBasic(),Basics.class);
        basics.setUname(log.getUname());
        basics.setTimestamp(Timestamp.valueOf(log.getTimestamp()));
        basics.setSystem("Linux");

        Hardware hardware = mapper.convertValue(lr.getHardware(),Hardware.class);
        hardware.setMac(log.getUname());
        hardware.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));

        List<Checks> licheck = lr.getBaseline();
        List<Baseline> libaseline = new LinkedList<>();
        for(Checks ch : licheck){
            Baseline bs = new Baseline();
            bs.setMac(log.getUname());
            bs.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));
            bs.setKey(ch.getKey());
            bs.setEvalued("1");
            bs.setRelVal(ch.getRel_val());
            bs.setResult(ch.getResult());
            libaseline.add(bs);
        }

        NetInfo ni = new NetInfo();
        ni.setMac(log.getUname());
        ni.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));
        List<String> lis = lr.getPort();
        StringBuilder stb = new StringBuilder();
        for (String li : lis) {
            stb.append(li).append(",");
        }
        ni.setOpenport(stb.toString().substring(0,stb.toString().length()-1));

        //添加到各类表中
        this.basicsService.insert(basics);
        this.hardwareService.insert(hardware);
        this.baselineService.multiinsert(libaseline);
        this.netInfoService.insert(ni);
        //发送日志消息
        this.logService.saveLog(new Log(log));
        return "添加成功";
    }


    @RequestMapping(value = "/insertAll",method = RequestMethod.POST)
    @ApiOperation(value = "插入一切",notes = "插入一切",httpMethod = "POST")
    public String insertAll(@RequestBody LinuxReceive allthing){
        ObjectMapper mapper = new ObjectMapper();
        Logs log = mapper.convertValue(allthing.getLog(),Logs.class);

        List<String> ls = Arrays.asList(log.getDes());
        System.out.println(ls.contains("basic"));
        if(ls.contains("basic")||ls.contains("linux_basic")){
            //实例化basic对象并添加到表里
            Basics basics = mapper.convertValue(allthing.getBasic(),Basics.class);
            basics.setUname(log.getUname());
            basics.setTimestamp(Timestamp.valueOf(log.getTimestamp()));
            if(ls.contains("linux_basic")){
                basics.setSystem("Linux");
            }
            this.basicsService.insert(basics);
        }
        if(ls.contains("hard")||ls.contains("linux_baseline")){
            //实例化hardware对象并添加到表里
            Hardware hardware = mapper.convertValue(allthing.getHardware(),Hardware.class);
            hardware.setMac(log.getUname());
            hardware.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));
            this.hardwareService.insert(hardware);
        }
        if(ls.contains("setting")||ls.contains("linux_baseline")){
            //实例化setting对象并添加到表里
            List<Checks> licheck = allthing.getBaseline();
            List<Baseline> libaseline = new LinkedList<>();
            boolean flag = ls.contains("linux_baseline");
            for(Checks ch : licheck){
                Baseline bs = new Baseline();
                bs.setMac(log.getUname());
                bs.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));
                bs.setKey(ch.getKey());
                if(flag){
                    bs.setEvalued("1");
                }else{
                    bs.setEvalued(ch.getEvalued());
                }
                bs.setRelVal(ch.getRel_val());
                bs.setResult(ch.getResult());
                libaseline.add(bs);
            }
            this.baselineService.multiinsert(libaseline);
        }
        if(ls.contains("service")){
            //实例化service对象并添加到表里
            List<ServiceReceive> liservice = allthing.getService();
            List<SystemService> lisystemserv= new LinkedList<>();
            for(ServiceReceive cr : liservice){
                SystemService bs = new SystemService();
                bs.setMac(log.getUname());
                bs.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));
                bs.setCaption(cr.getCaption());
                bs.setDescriptions(cr.getDescriptions());
                bs.setStartmode(cr.getStartmode());
                bs.setState(cr.getState());
                lisystemserv.add(bs);
            }
            //添加到syetemservice表中
            this.systemServiceService.multiinsert(lisystemserv);
        }
        if(ls.contains("port")||ls.contains("linux_baseline")){
            NetInfo ni = new NetInfo();

            ni.setMac(log.getUname());
            ni.setUpdateTime(Timestamp.valueOf(log.getTimestamp()));

            List<String> lis = allthing.getPort();
            StringBuilder stb = new StringBuilder();
            for (String li : lis) {
                stb.append(li).append(",");
            }
            ni.setOpenport(stb.toString().substring(0,stb.toString().length()-1));

            //添加到net_info表中
            this.netInfoService.insert(ni);
        }


        //发送日志消息
        this.logService.saveLog(new Log(log));
        return "添加成功";
    }


    @RequestMapping(value = "/queryBasicById",method = RequestMethod.GET)
    @ApiOperation(value = "根据mac搜索基础内容",notes = "根据mac搜索基础内容",httpMethod = "GET")
//    public Map<String, Object> queryBasicById(@RequestParam String mac){
    public List<Basics> queryBasicById(@RequestParam String mac){
        System.out.println(mac);
        return basicsService.selectById(mac);
    }

    @RequestMapping(value = "/queryHardwareById",method = RequestMethod.GET)
    @ApiOperation(value = "根据mac搜索硬件内容",notes = "根据mac搜索硬件内容",httpMethod = "GET")
    public List<Hardware> queryHardwareById(@RequestParam String mac){
        System.out.println(mac);
        return hardwareService.selectById(mac);
    }

    @RequestMapping(value = "/queryBaselineById",method = RequestMethod.GET)
    @ApiOperation(value = "根据mac搜索基线内容",notes = "根据mac搜索基线内容",httpMethod = "GET")
    public List<Baseline> queryBaselineById(@RequestParam String mac){
        System.out.println(mac);
        return baselineService.selectById(mac);
    }

    @RequestMapping(value = "/querySysServiceById",method = RequestMethod.GET)
    @ApiOperation(value = "根据mac搜索系统服务内容",notes = "根据mac搜索系统服务内容",httpMethod = "GET")
    public List<SystemService> querySysServiceById(@RequestParam String mac){
        return systemServiceService.selectById(mac);
    }

    @RequestMapping(value = "/queryNetInfoById",method = RequestMethod.GET)
    @ApiOperation(value = "根据mac搜索网络内容",notes = "根据mac搜索网络内容",httpMethod = "GET")
    public List<NetInfo> queryNetInfoById(@RequestParam String mac){
        return netInfoService.selectById(mac);
    }

    @RequestMapping(value = "/queryOneByMac",method = RequestMethod.GET)
    @ApiOperation(value = "根据mac搜索一个东西的内容",notes = "根据mac搜索一个东西的内容",httpMethod = "GET")
    public Object queryOneByMac(@RequestParam String mac, @RequestParam String type){
        if(type.equals("basics")){
            return basicsService.selectOneById(mac);
        }else if(type.equals("hardware")){
            return hardwareService.selectOneById(mac);
        }else if(type.equals("baseline")){
            return baselineService.selectOneById(mac);
        }else if(type.equals("sysservice")){
            return systemServiceService.selectOneById(mac);
        }else if(type.equals("net")){
            return netInfoService.selectOneById(mac);
        }else {
            return "数据格式错误！";
        }
    }

    @RequestMapping(value = "/queryByTime",method = RequestMethod.GET)
    @ApiOperation(value = "根据时间搜索一个东西的内容",notes = "根据时间搜索一个东西的内容",httpMethod = "GET")
    public Object queryByTime(@RequestParam String mac, @RequestParam String type,
                              @RequestParam Timestamp leftrange, @RequestParam Timestamp rightrange){
        if(type.equals("basics")){
            return basicsService.selectOneByTime(mac,leftrange,rightrange);
        }else if(type.equals("hardware")){
            return hardwareService.selectOneByTime(mac,leftrange,rightrange);
        }else if(type.equals("baseline")){
            return baselineService.selectOneByTime(mac,leftrange,rightrange);
        }else if(type.equals("sysservice")){
            return systemServiceService.selectOneByTime(mac,leftrange,rightrange);
        }else if(type.equals("net")){
            return netInfoService.selectOneByTime(mac,leftrange,rightrange);
        }else {
            return "数据格式错误！";
        }
    }


//    @RequestMapping(value = "/test",method = RequestMethod.GET)
//    @ApiOperation(value = "test",notes = "test",httpMethod = "GET")
//    public String test(@Valid Basics basics){
//        return basics.getUname();
//    }

}
